﻿using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace KL.UFrame.Data.DynamicLinqExtension
{
    public static class DynamicExtention
    {
        /// <summary>
        /// 将Filter生成Where参数
        /// 用法：
        /// var filters = new Filter[]  
        ///{  
        ///    new Filter("UserName","yubaolee", FilterContrac.Like),  
        ///    new Filter("UserType","administrator", FilterContract.Equal)  
        ///};  
        ///var users = _context.UserInfoes.Where(filters);  
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="filters"></param>
        /// <param name="any">true：所有Filter全满足才为真；false：任意一个Filter满足即为真</param>
        /// <returns></returns>
        public static IQueryable<T> Where<T>(this IQueryable<T> query, IEnumerable<Filter> filters, bool any = false)
        {
            var param = DynamicLinq.CreateLambdaParam<T>("c");
            Expression body = Expression.Constant(true); //初始默认一个true  
            foreach (var filter in filters)
            {
                body = any ? body.Or(param.GenerateBody<T>(filter)) : body.AndAlso(param.GenerateBody<T>(filter));
                //这里可以根据需要自由组合  
            }
            var lambda = param.GenerateTypeLambda<T>(body); //最终组成lambda  
            return query.Where(lambda);
        }
    }
}